package com.website.system.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.website.common.controller.BaseController;
import com.website.common.warpper.ResultMap;
import com.website.config.poi.PoiUtils;
import com.website.config.poi.RespBean;
import com.website.core.aop.MyAop;
import com.website.core.util.DateUtil;
import com.website.system.model.Drug;
import com.website.system.model.Pharmacy;
import com.website.system.model.vo.DrugVO;
import com.website.system.service.DrugService;
import com.website.system.service.PharmacyService;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("manage/drug")
public class DrugController extends BaseController {

    @Resource
    private DrugService DrugService;
    @Resource
    private PharmacyService pharmacyService;


    /**
     * 跳转到 药品中心
     */
    @RequestMapping("/{type}")
    public String article(Model model, @PathVariable String type) {
        model.addAttribute("type", type);
        return "manage/drug";
    }

    /**
     * 显示所有
     *
     * @return
     */
    @MyAop
    @RequestMapping("/findAll")
    @ResponseBody
    public ResultMap findAll(@RequestParam Integer page, @RequestParam Integer limit, @RequestParam(required = false) String name) {
        ResultMap<List<DrugVO>> resultMap = new ResultMap<>(SUCCESS_CODE, SUCCESS_MSG, null, null);
        Page<Drug> pageInfo = new Page<>(page, limit);
        Wrapper<Drug> wrapper = new EntityWrapper<>();
        // wrapper =  wrapper.eq("type", type);
        if (name != null && !name.equals("")) {
            wrapper = wrapper.like("name", name);
        }
        List<Drug> DList = DrugService.selectPage(pageInfo, wrapper.orderBy("id", true)).getRecords();
        resultMap.setCount(DrugService.selectCount(wrapper));
        List<DrugVO> drugVOList = new ArrayList<>();
        for (Drug drug : DList) {
            DrugVO drugVO = new DrugVO();
            Pharmacy pharmacy = pharmacyService.findById(drug.getPid());
            drugVO.setId(drug.getId());
            drugVO.setPid(drug.getPid());
            drugVO.setUrl(drug.getUrl());
            drugVO.setName(drug.getName());
            drugVO.setBuytime(drug.getBuytime());
            drugVO.setUpdatetime(drug.getUpdatetime());
            drugVO.setEffect(drug.getEffect());
            drugVO.setPrice(drug.getPrice());
            drugVO.setPname(pharmacy.getPname());
            drugVOList.add(drugVO);

        }
        resultMap.setData(drugVOList);
        return resultMap;
    }

    /**
     * 把对象储存在model里
     * 查看页面 药品信息
     */
    @RequestMapping("/read/{id}")
    public String DrugRead(Model model, @PathVariable Integer id) {
        Drug drug = DrugService.selectById(id);
        model.addAttribute("drug", DrugService.selectById(id));
        Pharmacy pharmacy = pharmacyService.findById(drug.getPid());
        model.addAttribute("pharmacy", pharmacy);
        return "manage/DrugRead";
    }

    /**
     * 把对象存在model中
     * 进入到修改页面并显示药品信息
     */
    @RequestMapping("/toUpdate/{id}")
    public String getAssociation(Model model, @PathVariable Integer id) {
        Drug drug = DrugService.selectById(id);
        model.addAttribute("drug", DrugService.selectById(id));
        Pharmacy pharmacy = pharmacyService.findById(drug.getPid());
        model.addAttribute("pharmacy", pharmacy);
        return "manage/drugUpdate";
    }

    /**
     * 修改信息
     *
     * @param drug
     * @return
     */

    @RequestMapping("/update")
    public String update(Drug drug) {
        try {
            DrugService.updateById(drug);
            return SUCCESS_MSG;
        } catch (Exception e) {
            e.printStackTrace();
            return ERROR_MSG;
        }

    }

    /**
     * 跳转到添加药品页面
     */
    @RequestMapping("/toAdd")
    public String todrugAdd() {
        return "manage/drugAdd";
    }

    /***
     * 添加药品
     * @param drug
     * @return
     */
    @RequestMapping("/AddDrug")
    public String drugAdd(Drug drug) {
        try {
            drug.setUrl("files/image/" + drug.getUrl() + ".jpg");
            DrugService.insert(drug);
            return SUCCESS_MSG;
        } catch (Exception e) {
            return ERROR_MSG;
        }


    }

    /**
     * 删除药品
     */
    @ResponseBody
    @RequestMapping("/del/{id}")
    public String drugdel(@PathVariable Integer id) {
        try {
            DrugService.deleteById(id);
            return SUCCESS_MSG;
        } catch (Exception e) {
            return ERROR_MSG;
        }
    }

    /**
     * 动态加载药品类别
     */
    @ResponseBody
    @RequestMapping(value = "/Pharmacy", method = RequestMethod.POST)
    public List<Pharmacy> Pharmacy() {
        Wrapper<Pharmacy> p = new EntityWrapper<>();
        List<Pharmacy> list = pharmacyService.selectList(p);
        return list;
    }

    /**
     * 上传图片(网站新闻) layUI2.0上传
     */
    @RequestMapping(path = "/AddUrl", method = RequestMethod.POST)
    @ResponseBody
    public ResultMap fileUpload(@RequestParam("file") MultipartFile file) {
        String url = DateUtil.getAllTime();
        try {
            String fileSavePath = getFileUploadPath() + "/image/" + url + ".jpg";
            file.transferTo(new File(fileSavePath));
            return getResultMap(SUCCESS_CODE, url);
        } catch (Exception e) {
            return getResultMap(ERROR_CODE, "图片上传失败，请稍后重试，或联系管理员");
        }
    }

    /**
     * 导入导出报表
     */
    @MyAop
    @RequestMapping(value = "/exportDrug", method = RequestMethod.GET)
    public ResponseEntity<byte[]> exportDrug() {
        return PoiUtils.exportDrugs2Excel(DrugService.exportDrug());
    }

    @RequestMapping(value = "/importDrug", method = RequestMethod.POST)
    public RespBean importDrug(MultipartFile file) {
        List<Drug> drugs = PoiUtils.importDrug2List(file);
        if (DrugService.addDrug(drugs) == drugs.size()) {
            return RespBean.ok("导入成功!");
        }
        return RespBean.error("导入失败!");
    }
    /*@RequestMapping(value = "/importDrug")
    public String exImport(@RequestParam(value = "filename")MultipartFile file, HttpSession session) {

        boolean a = false;

        String fileName = file.getOriginalFilename();

        try {
            a = DrugService.batchImport(fileName,file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/manage/drug";
    }*/

}
